package com.rc.saas.mini.controller.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.car.TenantCarNumber;
import com.rc.saas.mini.model.car.TenantCarNumberExample;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.rc.RcMemberFlag;
import com.rc.saas.mini.service.car.TenantCarNumberService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.rc.RcMemberFlagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/4/26
 */

@Controller
@RequestMapping("/carNumber")
@Api(tags = "06.车牌库")
public class CarNumberController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(CarNumberController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private TenantCarNumberService tenantCarNumberService;
    @Autowired
    private RcMemberFlagService rcMemberFlagService;

    /**
     * 车牌库列表
     */
    @ResponseBody
    @RequestMapping("/listCarNum")
    @ApiOperation(value = "车牌库列表(需要登陆)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<List<String>> listCarNum(HttpServletRequest request) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        List<String> list = tenantCarNumberService.listCarNum(member);
        return DataTResponse.SUCCESS_DATA(list);
    }

    /**
     * 车牌库分页列表
     */
    @ResponseBody
    @RequestMapping("/listPageCarNum")
    @ApiOperation(value = "车牌库分页列表(需要登陆)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", paramType = "query", value = "页码（默认1）", required = false),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "页大小（默认10）", required = false)})
    public DataTResponse<PageInfo<TenantCarNumber>> listPageCarNum(HttpServletRequest request, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());

        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (StringUtils.isBlank(member.getMobile())) {
            return DataTResponse.FAIL("手机号未绑定");
        }
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<TenantCarNumber> pageInfo = tenantCarNumberService.listPageCarNum(member, pageNo, pageSize);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }


    /**
     * 新增/修改车牌
     */
    @ResponseBody
    @RequestMapping("/saveOrUpdateCarNumber")
    @ApiOperation(value = "新增/修改车牌(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "numberId", value = "id", paramType = "query", required = false),
            @ApiImplicitParam(name = "carArea", value = "车牌所属区域:粤", paramType = "query", required = true),
            @ApiImplicitParam(name = "carLetter", value = "车牌所属城市编号:A", paramType = "query", required = true),
            @ApiImplicitParam(name = "carNum", value = "车牌号码", paramType = "query", required = true),
            @ApiImplicitParam(name = "carType", value = "车辆型号", paramType = "query", required = false),
            @ApiImplicitParam(name = "carVin", value = "车架号", paramType = "query", required = false),
            @ApiImplicitParam(name = "endurance", value = "续航km", paramType = "query", required = false),
            @ApiImplicitParam(name = "carImg", value = "图标地址", paramType = "query", required = false),
            @ApiImplicitParam(name = "productionYear", value = "生产年份", paramType = "query", required = false),
            @ApiImplicitParam(name = "carBelong", value = "车牌所属城市（全称）", paramType = "query", required = false),
    })
    public DataTResponse<String> saveOrUpdateCarNumber(HttpServletRequest request, TenantCarNumber carNumber) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        //拼接成完整的车牌号
        String fullCarNum = carNumber.getCarArea() + carNumber.getCarLetter() + carNumber.getCarNum();
        carNumber.setCarNo(fullCarNum);

        TenantCarNumber oldData = carNumber;
        //用户车辆判断 ，车是否企业，用户是否企业
        TenantCarNumberExample tenantCarNumberExample = new TenantCarNumberExample();
        tenantCarNumberExample.createCriteria().andIsEnterpriseEqualTo("1").andCarNoEqualTo(carNumber.getCarNo()).andMemberIdIsNull();
        tenantCarNumberExample.setOrderByClause("created_time desc");
        TenantCarNumber entTenantCarNumber = tenantCarNumberService.selectByExample(tenantCarNumberExample).stream().findFirst().orElseGet(() -> null);
        if (entTenantCarNumber != null) {
            RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(member.getMemberId());

            if (rcMemberFlag == null || rcMemberFlag.getEnterpriseId() == null) {
                return DataTResponse.FAIL("您还未进行企业认证，无法添加企业用车");
            }
            if (!rcMemberFlag.getEnterpriseId().equals(entTenantCarNumber.getEnterpriseMemberId())) {
                return DataTResponse.FAIL("当前车辆在企业下不存在");
            }
            carNumber = entTenantCarNumber;
            carNumber.setIsEnterprise("1");
            carNumber.setMemberId(member.getMemberId());
            carNumber.setCarNo(fullCarNum);
            carNumber.setCarArea(oldData.getCarArea());
            carNumber.setCarLetter(oldData.getCarLetter());
            carNumber.setCarType(oldData.getCarType());
            carNumber.setEndurance(oldData.getEndurance());
            carNumber.setProductionYear(oldData.getProductionYear());
            carNumber.setCarImg(oldData.getCarImg());
            carNumber.setCarNum(oldData.getCarNum());
            if (oldData.getCarVin() != null) {
                carNumber.setCarVin(oldData.getCarVin());
            }
            if (oldData.getCarBelong() != null) {
                carNumber.setCarBelong(oldData.getCarBelong());
            }
        }

        TenantCarNumberExample tenantCarNumberAddExample = new TenantCarNumberExample();
        tenantCarNumberAddExample.createCriteria().andMemberIdIsNotNull().andCarNoEqualTo(carNumber.getCarNo());
        tenantCarNumberAddExample.setOrderByClause("created_time desc");
        TenantCarNumber otherTenantCarNumber = tenantCarNumberService.selectByExample(tenantCarNumberAddExample).stream().findFirst().orElseGet(() -> null);
        if (otherTenantCarNumber != null) {
            return DataTResponse.FAIL("当前车辆已被其它用户绑定~");
        }


        logger.info("carnumber.saveOrUpdateCarNumber.carnum:{}", fullCarNum);
        if (StringUtils.isEmpty(fullCarNum)) {
            return DataTResponse.FAIL("车牌号不能为空");
        }
        if (StringUtils.isEmpty(carNumber.getCarArea()) || StringUtils.isEmpty(carNumber.getCarLetter())) {
            return DataTResponse.FAIL("车牌号不完整");
        }
        if (fullCarNum.matches(HttpConstant.CAR_NUMBER_REGEX)) {
            //查重
//            TenantCarNumberExample example = new TenantCarNumberExample();
//            example.createCriteria().andMemberIdEqualTo(member.getMemberId())
//                    .andCarAreaEqualTo(carNumber.getCarArea()).andCarNumEqualTo(carNumber.getCarNum())
//                    .andCarLetterEqualTo(carNumber.getCarLetter()).andCarTypeEqualTo(carNumber.getCarType());
//            TenantCarNumber tenantCarNumber = tenantCarNumberService.selectByExample(example).stream().findFirst().orElseGet(() -> null);
//
//            if (tenantCarNumber != null && carNumber.getNumberId() == null) {
//                return DataTResponse.FAIL("车牌不能重复");
//            }
            tenantCarNumberService.saveOrUpdateCarNumber(member, carNumber);
        } else {
            return DataTResponse.FAIL("车牌号格式不正确!");
        }
        return DataTResponse.SUCCESS();
    }

    /**
     * 设置默认车牌号
     */
    @RequestMapping("/setDefaultCarNumber")
    @ResponseBody
    @ApiOperation(value = "设置默认车牌号(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "numberId", paramType = "query", value = "车牌号ID", required = true)
    })
    public DataTResponse<String> setDefaultCarNumber(HttpServletRequest request, Long numberId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        try {
            tenantCarNumberService.updateDefault(member, numberId);
        } catch (Exception e) {
            e.printStackTrace();
            return DataTResponse.FAIL("设置失败");
        }
        return DataTResponse.SUCCESS();
    }

    /**
     * 获取默认车牌号
     */
    @RequestMapping("/findDefultCarNum")
    @ResponseBody
    @ApiOperation(value = "获取车牌号(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<TenantCarNumber> findDefultCarNum(HttpServletRequest request) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        if (member == null || StringUtils.isBlank(member.getMobile())) {
            return DataTResponse.FAIL_LOGIN();
        }
        TenantCarNumberExample example = new TenantCarNumberExample();
        example.createCriteria().andMemberIdEqualTo(member.getMemberId()).andTenantCodeEqualTo(member.getTenantCode()).andIsDefaultEqualTo("1");
        List<TenantCarNumber> tenantCarNumbers = tenantCarNumberService.selectByExample(example);
        if (tenantCarNumbers != null && tenantCarNumbers.size() > 0) {
            return DataTResponse.SUCCESS_DATA(tenantCarNumbers.get(0));
        } else {
            return DataTResponse.SUCCESS();
        }

    }

    /**
     * 根据车牌Id获取车牌
     */
    @ResponseBody
    @RequestMapping("/selectCarNumberById")
    @ApiOperation(value = "根据车牌Id获取车牌", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "numberId", paramType = "query", value = "车牌号ID", required = true)
    })
    public DataTResponse<TenantCarNumber> selectCarNumberById(HttpServletRequest request, Long numberId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        TenantCarNumberExample example = new TenantCarNumberExample();
        example.createCriteria().andTenantCodeEqualTo(member.getTenantCode()).andNumberIdEqualTo(numberId).andMemberIdEqualTo(member.getMemberId());
        List<TenantCarNumber> tenantCarNumbers = tenantCarNumberService.selectByExample(example);
        if (tenantCarNumbers != null && tenantCarNumbers.size() > 0) {

            return DataTResponse.SUCCESS_DATA(tenantCarNumbers.get(0));
        } else {
            return DataTResponse.FAIL("车牌号不存在");
        }

    }

    /**
     * 删除车牌
     */
    @ResponseBody
    @RequestMapping("/deleteCarNumber")
    @ApiOperation(value = "删除车牌(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "numberId", value = "车牌号id", required = true, paramType = "query")
    public DataTResponse<String> deleteCarNumber(HttpServletRequest request, Long numberId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        TenantCarNumber carNumber = tenantCarNumberService.selectByPrimaryKey(numberId);
        if (numberId != null) {
            if (member.getMemberId().equals(carNumber.getMemberId())) {
                try {
                    //默认车牌号不能删除
                    if ("1".equals(carNumber.getIsDefault())) {
                        return DataTResponse.FAIL("默认车牌号不能删除");
                    }
                    tenantCarNumberService.deleteByPrimaryKey(numberId);

                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return DataTResponse.FAIL("删除失败");
                }
            } else {
                return DataTResponse.FAIL("只能删除自己的车牌");
            }
        }
        return DataTResponse.SUCCESS();
    }
}
